<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <!-- v-if="hasPointsPermission('excel_import')" -->

          <el-button
            v-permission="'excel_import'"
            type="warning"
            size="small"
            @click="$router.push('/import?type=user')"
          >
            excel导入
          </el-button>
          <!-- v-if="hasPointsPermission('excel_export')" -->
          <el-button
            v-permission="'excel_export'"
            type="danger"
            size="small"
            @click="exportExcel"
          >
            excel导出
          </el-button>
          <!-- v-if="hasPointsPermission('p-em-add')" -->

          <el-button
            v-permission="'p-em-add'"
            type="primary"
            size="small"
            @click="addEmployeeFn"
          >
            新增员工
          </el-button>
        </template>
      </page-tools>

      <el-card v-loading="isLoading" style="margin-top: 10px">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" :index="indexMethod" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{ row }">
              <img
                v-imgerror="defaultImg"
                class="staff"
                :src="row.staffPhoto || nullImage"
                alt=""
              />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            :formatter="formatterData"
          />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{ row }">
              <!-- 获取到时间 -->
              {{ formatTime(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{ row }">
              <!-- v-if="hasPointsPermission('p-em-look')" -->

              <el-button
                v-permission="'p-em-look'"
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >
                查看
              </el-button>
              <!-- v-if="hasPointsPermission('assign_role')" -->

              <el-button
                v-permission="'assign_role'"
                type="text"
                size="small"
                @click="assignRoleClick(row.id)"
              >
                分配角色
              </el-button>
              <!-- v-if="hasPointsPermission('emp_delete')"s -->

              <el-button
                v-permission="'emp_delete'"
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <!-- size-change  页容量发生变化  current-change 当前页码发生改变-->
          <el-pagination
            :current-page="page"
            :page-size="size"
            :page-sizes="[10, 20, 30, 40]"
            layout="total,sizes,prev, pager, next,jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <!-- sync  将修改权交给子组件 -->
      <add-employee :show-dialog.sync="showDialog" />
    </div>
    <assignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeesListApi, delEmployeeApi } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import addEmployee from './components/add-employee.vue'
import assignRole from './components/assign-role.vue'
import avatar from '@/assets/common/add-circle.png'

// import { mapGetters } from 'vuex'

// 使用mixins的方式  1.先导入mixins所在的文件 2.把mixins混入当前组件中(mixins: [index])
import permission from '@/mixins/permission'
// 导入dayjs
import dayjs from 'dayjs'
export default {
  name: 'Employees',
  components: {
    addEmployee,
    assignRole
  },
  mixins: [permission],
  data() {
    return {
      list: [],
      page: 1, // 当前页
      size: 10, // 每页条数
      total: 0, // 总数
      isLoading: false,
      showDialog: false,
      defaultImg: avatar,
      nullImage:
        'https://img2.baidu.com/it/u=2203692359,101708973&fm=253&fmt=auto&app=138&f=PNG?w=401&h=401',
      showRoleDialog: false,
      userId: ''
    }
  },
  computed: {
    // ...mapGetters(['roles'])
  },
  created() {
    // console.log(this.$slots)
    // this.$slots  作用 :  获取父组件传过来的插槽信息
    this.getEmployeesList()
  },
  methods: {
    // 获取按钮权限------>  mixins
    // hasPointsPermission(points) {
    //   // return this.roles.points.includes(points)
    //   // 添加可选链
    //   return this.roles?.points?.includes(points)
    // },
    // 分配角色打开面板获取id
    assignRoleClick(id) {
      this.showRoleDialog = true
      this.userId = id
    },

    // 导出excel
    async exportExcel() {
      const headersArr = [
        '姓名',
        '手机号',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      const {
        data: { rows }
      } = await getEmployeesListApi(1, this.total)
      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const data = this.formateData2Array(headersArr, rows, headersRelations)
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A1', 'B1:F1', 'G1:G1']
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: headersArr, // excel表头
          data:
            // excel数据
            // 导出的数据必须是二维数组
            data,
          filename: '员工信息', // 导出文件的文件名
          autoWidth: true, // 单元格宽度是否自适应
          bookType: 'xlsx', // 文件的后缀名
          multiHeader,
          merges
        })
      })
    },
    // 导出excel
    formateData2Array(headersArr, rows, headersRelations) {
      const arr = []
      rows.forEach((item) => {
        const tempArray = []
        headersArr.forEach((key) => {
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          if (englishKey === 'formOfEmployment') {
            const hireObj = EmployeeEnum.hireType.find(
              (item) => item.id === Number(value)
            )
            value = hireObj ? hireObj.value : '未知'
          }
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = value ? this.formatTime(value) : ''
          }
          tempArray.push(value)
        })
        arr.push(tempArray)
      })
      return arr
    },
    // 处理时间
    formatTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    // 格式化数据
    formatterData(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      // 正式 ID=1  非正式id=2
      // if (cellValue === 1) {
      //   return '正式'
      // }
      // if (cellValue !== 1) {
      //   return '非正式'
      // }
      const hireObj = EmployeeEnum.hireType.find(
        (item) => item.id === Number(cellValue)
      )
      return hireObj ? hireObj.value : '未知'
    },
    // 序号显示方法
    indexMethod(index) {
      return (this.page - 1) * this.size + index + 1
    },
    async getEmployeesList() {
      this.isLoading = true
      // 获取数据
      const { data } = await getEmployeesListApi(this.page, this.pageSize)
      // 数据传参
      this.list = data.rows
      this.total = data.total
      this.isLoading = false
    },
    /**
     * 页容量改变
     */
    handleSizeChange(val) {
      this.size = val
      this.getEmployeesList()
    },
    /**
     * 页码改变
     */
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeesList()
    },
    // 删除工具
    delEmployee(id) {
      this.$confirm('您确定要删除吗？该操作不可逆哟', '温馨提示')
        .then(async() => {
          await delEmployeeApi(id)
          if (this.list.length === 1 && this.page > 1) {
            this.page--
          }
          this.$message.success('删除成功')
          this.getEmployeesList()
        })
        .catch(() => {})
    },
    // 添加打开
    addEmployeeFn() {
      this.showDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
